package com.nondo.rdp.auth.listener;

import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.domain.UserLoginLog;
import com.nondo.rdp.auth.event.PointApplicationEvent;
import com.nondo.rdp.auth.service.UserLoginLogService;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.auth.event.LoginApplicationEvent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 用户登录监听器
 */
@Component
public class LoginApplicationListener implements ApplicationListener<LoginApplicationEvent> {
	@Autowired
	private UserService userService;
	
    @Autowired
    private UserLoginLogService userLoginLogService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void onApplicationEvent(LoginApplicationEvent event) {
        System.out.println("接收到事件：" + event.getClass());

        //添加积分
        applicationEventPublisher.publishEvent(new PointApplicationEvent(this, event.getUser(), PointApplicationListener.TYPE_LOGIN));

        //增加登录日志
        addUserLoginLog(event);
        
        //更新用户信息
        updateUser(event);
        
    }

    /**
     * 添加登录日志
     */
    public void addUserLoginLog(LoginApplicationEvent event) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUser(event.getUser());

        this.userLoginLogService.save(userLoginLog);
    }
    
    /**
     * 更新用户信息
     */
    public void updateUser(LoginApplicationEvent event) {
    	User user = event.getUser();
        this.userService.save(user);
    }
}
